<template>
  <div class="indicator-set">
    <div class="setting-content">
      <p class="data-statistic-title">设置指标</p>
      <p class="detail-tile">通过选择某个阶段的某个CRF表中的某道题目作为统计指标</p>
    </div>
    <avue-form
      :option="option"
      v-model="form"
      style="margin-top: 10px"
      @submit="handleSubmit"
    ></avue-form>
    <div class="setting-content" style="margin-top: 10px">
      <p class="data-statistic-title">指标查询</p>
      <p class="detail-tile">该数据库已经设置的指标</p>
    </div>
    <avue-crud
      style="margin-top: 20px"
      :option="tableOption"
      v-model:search="search"
      v-model:page="page"
      v-model="tableForm"
      :table-loading="loading"
      :data="tableData"
      ref="crud"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    ></avue-crud>
    <el-dialog v-model="isIndicator" title="" width="1200" body-class="QR-code-dialog-body">
      <VFormRender
        :form-json="formJson"
        :form-data="formData"
        :option-data="optionData"
        ref="vFormRef"
        @formChange="onFormDataChange"
      >
      </VFormRender>
    </el-dialog>
  </div>
</template>
<script setup>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
} from '@/api/multipleindicators/multipleIndicators';
import { getCrfDetail } from '@/api/crf/crf.js';
import VFormRender from '@/components/form-render/index.vue';
import { useStore } from 'vuex';
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
const crud = ref(null);
const store = useStore();
const selectTab = ref(1);
const routerQuery = ref({});
routerQuery.value = route.query;

const formJson = ref({});
const vFormRef = ref(null);
const formData = ref({});
const optionData = ref({});

let form = ref({});
let option = ref({
  submitText: '提 交',
  emptyBtn: false,
  menuSpan: 24,
  menuPosition: 'left',
  // submitBtn: false,
  column: [
    {
      label: '指标名称',
      prop: 'name',
      type: 'input',
      span: 5,
      rules: [
        {
          required: true,
          message: '请输入指标名称',
          trigger: 'blur',
        },
      ],
    },
    {
      label: '选择分组',
      prop: 'groupId',
      type: 'select',
      dicUrl: `/api/blade-group/group/groupListOfTrial?trialId=${routerQuery.value.trialId}`,
      props: {
        label: 'name',
        value: 'id',
      },
      cascader: ['phaseId'],
      span: 5,
      rules: [
        {
          required: true,
          message: '请选择分组',
          trigger: 'blur',
        },
      ],
      filterable: true,
      overHidden: true,
    },
    {
      label: '选择阶段',
      prop: 'phaseId',
      type: 'select',
      dicUrl: `/api/blade-phase/phase/treeWithCrf?groupId={{groupId}}`,
      props: {
        label: 'title',
        value: 'id',
      },
      cascader: ['crfId'],
      span: 5,
      rules: [
        {
          required: true,
          message: '请选择阶段',
          trigger: 'blur',
        },
      ],
      filterable: true,
      overHidden: true,
    },
    {
      label: 'CRF表',
      prop: 'crfId',
      type: 'select',
      dicUrl: `/api/blade-phasecrf/phaseCrf/listOfPhase?phaseId={{phaseId}}`,
      props: {
        label: 'crfName',
        value: 'crf',
      },
      span: 5,
      rules: [
        {
          required: true,
          message: '请选择CRF表',
          trigger: 'blur',
        },
      ],
      filterable: true,
      overHidden: true,
      change: ({ value, column }) => {
        form.value.indicatorId = '';
      },
    },
    {
      label: '',
      prop: 'indicatorId',
      labelWidth: 10,
      span: 4,
      rules: [
        {
          required: true,
          message: '请选择题目',
          trigger: 'blur',
        },
      ],
      click: ({ value, column }) => {
        if (form.value.groupId != '' && form.value.phaseId != '' && form.value.crfId != '') {
          initGetCrfDetail(form.value.crfId);
        }
      },
    },
    {
      label: '图表展示',
      prop: 'chartType',
      type: 'radio',
      border: true,
      dicData: [
        { label: '柱状图', value: '1' },
        { label: '饼状图', value: '2' },
        { label: '折线图', value: '3' },
      ],
      span: 24,
      rules: [
        {
          required: true,
          message: '请选择图表展示',
          trigger: 'blur',
        },
      ],
    },
  ],
});

let isIndicator = ref(false);
const sendCheckedList = computed(() => store.getters.checkedList);
watch(
  () => sendCheckedList.value,
  (newVal, oldVal) => {
    if (newVal.length === 1) {
      form.value.indicatorId = newVal[0];
      isIndicator.value = false;
    }
  },
  { deep: true } // 深度监听对象/数组变化
);
const initGetCrfDetail = async crfId => {
  const { data: res } = await getCrfDetail(crfId);
  if (res.code == 200) {
    store.commit('SET_CHECKED_LIST', []);
    localStorage.removeItem('checkedList');
    isIndicator.value = true;
    localStorage.setItem('sendIsIndicator', true);
    formJson.value = JSON.parse(res.data.content);
    nextTick(() => {
      vFormRef.value.setFormJson(formJson.value);
    });
    setTimeout(() => {
      localStorage.removeItem('sendIsIndicator');
    }, 1000);
  }
};

let tableOption = ref({
  height: 'auto',
  calcHeight: 30,
  tip: false,
  searchShow: true,
  searchMenuSpan: 12,
  searchMenuPosition:'right',
  border: true,
  index: false,
  selection: false,
  dialogClickModal: false,
  align: 'center',
  // menu: false,
  addBtn: false,
  // delBtn:false,
  viewBtn:false,
  editBtn: false,
  searchLabelWidth: 120,
  column: [
    {
      label: '项目指标名称',
      prop: 'name',
      type: 'input',
      search:true,
    },
    {
      label: '所选指标',
      prop: 'indicator',
      type: 'input',
    },
    {
      label: '图标类型',
      prop: 'chartType',
      type: 'radio',
      border: true,
      search:true,
      dicData: [
        { label: '柱状图', value: '1' },
        { label: '饼状图', value: '2' },
        { label: '折线图', value: '3' },
      ],
    },
    {
      // 下划线隔开：组id(groupId)_阶段id(phaseId)_阶段crfId(phaseCrfId)_指标(indicatorId)
      label: '指标内容',
      prop: 'content',
      type: 'input',
      hide:true,
    },
    {
      label: '所属业务',
      prop: 'trial',
      type: 'input',
      hide: true,
    },
  ],
});
let search = ref({});
const tableForm = ref({});
const query = ref({});
let loading = ref(false);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
let tableData = ref([]);
const handleSubmit = (forms, done) => {
  forms.trial = routerQuery.value.trialId;
  forms.content = `${forms.groupId}_${forms.phaseId}_${forms.crfId}_${forms.indicatorId}`;
  forms.indicator = localStorage.getItem('sendCheckedTitle');
  add(forms).then(res => {
    onLoad(page.value);
    ElMessage.success('操作成功!');
    localStorage.removeItem('sendCheckedTitle');
    for (const key in form.value) {
      form.value[key] = "";
    }
    done();
  });
};
const rowDel = row => {
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(row.id);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};
const searchReset = () => {
  query.value = {};
  onLoad(page.value);
};

const searchChange = (params, done) => {
  query.value = params;
  page.value.currentPage = 1;
  onLoad(page.value, params);
  done();
};
const currentChange = currentPage => {
  page.value.currentPage = currentPage;
};

const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
};

const refreshChange = () => {
  onLoad(page.value, query.value);
};

const onLoad = (page, params) => {
  loading.value = true;
  let values = {
    descs: 'create_time',
    ...params,
    trial:routerQuery.value.trialId,
  };
  getList(page.currentPage, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    page.total = DATA.total;
    tableData.value = DATA.records;
    loading.value = false;
    // selectionClear();
  });
};
</script>
<style scoped>
.indicator-set {
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: column;
}
.setting-content {
  border: 1px solid #3c8dbc;
  border-left-width: 5px;
  border-radius: 3px;
  padding: 0px 10px;
  background: #f2f7fa;
  display: flex;
  align-items: center;
}
.data-statistic-title {
  line-height: 36px;
  font-size: 16px;
  align-items: center;
  justify-content: center;
  margin: 0px;
}
.detail-tile {
  margin: 0px 10px;
  /* color: #777; */
  line-height: 36px;
  font-size: 13px;
}
</style>
